package com.inhim.pjhim.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

public class WrapContentHeightViewPager extends ViewPager {
    private int mPosition;
    private int oldPositon;
    private static final String TAG = "WrapContentHeightViewPager";

    /** * Constructor * * @param context the context */
    public WrapContentHeightViewPager(Context context) {
        super(context);
    }

    /**
     * * Constructor * * @param context the context * @param attrs the attribute
     * set
     */
    public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        /*int height = 0;
        Log.i("zhiqiang", "getChildCount()="+getChildCount()+"");
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.measure(widthMeasureSpec,
                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            int h = child.getMeasuredHeight();
            if (h > height)
                height = h;
        }
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
                MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);*/
        int height = 0;
       if(mPosition==1){
           int index = getCurrentItem();
           View v = getChildAt(index);
           if (v != null) {
               v.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
               height = v.getMeasuredHeight();
           }
       }else{
           for (int i = 0; i < getChildCount(); i++) {
               View child = getChildAt(i);
               child.measure(widthMeasureSpec,
                       MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
               int h = child.getMeasuredHeight();
               if (h > height)
                   height = h;
           }
       }
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        final ViewPager pager = this;
        pager.addOnPageChangeListener(new SimpleOnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                mPosition = position;
                requestLayout();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == 2) {
                    requestLayout();
                }
            }

        });

    }

}
